/*
 * @Author: Superficial
 * @Date: 2021-02-22 17:08:46
 * @LastEditTime: 2021-03-18 14:29:50
 * @Description: theme
 */

import { ref, inject } from "vue";
import cookies from "js-cookie";
import { get } from "./storage";
const DARK_THEME_QUERY = '(prefers-color-scheme: dark)'
const LIGHT_THEME_QUERY = '(prefers-color-scheme: light)'
const themes = ["default", "dark"]

export const getClientLocalTheme = () => {
  // local theme
  const historyTheme = get('theme')
  if (historyTheme) {
    return historyTheme === 'dark'
      ? 'dark'
      : 'default'
  }
  // system theme
  if (window.matchMedia(DARK_THEME_QUERY).matches) {
    return 'dark'
  }
  if (window.matchMedia(LIGHT_THEME_QUERY).matches) {
    return 'default'
  }
  // not specified || not support
  return 'default'
}

const createThemeStore = (defaultTheme) => {
  const theme = ref(defaultTheme)

  // 设置主题
  const setTheme = (newTheme) => {
    if (themes.includes(newTheme) && newTheme !== theme.value) {
      theme.value = newTheme
      cookies.set("theme", newTheme)
      localStorage.setItem("theme", newTheme)
    }
  }

  const toggle = () => {
    const changeTheme =  theme.value === "dark" ? "default" : "dark"
    return setTheme(changeTheme)
  }

  const bindClientSystem = () => {
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change',
      ({matches}) => matches && set('dark')
    )
    window.matchMedia('(prefers-color-scheme: light)').addEventListener('change',
      ({matches}) => matches && set('default')
    )
  }

  return {
    theme,
    setTheme,
    toggle,
    bindClientSystem
  }
}

export const createTheme = (defaultTheme='default') => {
  const themeStore = createThemeStore(defaultTheme)

  return {
    ...themeStore,
    install(app) {
      app.provide("theme", themeStore)
    }
  }
}

export const useTheme = () => {
  return inject("theme")
}